package com.drojian;

import android.Manifest;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    public static final int REQUEST_WRITE_EXTERNAL_STORAGE = 12;
    private AlertDialog goSettingDialog;
    private List<File> fileList = new ArrayList<>();
    private RecyclerView rvFileList;
    private TextView tvScanPath;
    private final int SCAN_LOADING_PATH = 100;
    private final int SCAN_COMPLETE = 101;
    private Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SCAN_LOADING_PATH:
                    File file = (File) msg.obj;
                    tvScanPath.setText(file.getAbsolutePath());
                    break;
                case SCAN_COMPLETE:
                    fileAdapter.setNewData(fileList);
                    if (fileList.size() == 0) {
                        tvScanPath.setText("无数据");
                    } else {
                        tvScanPath.setText(String.format("已扫描到%d个media文件", fileList.size()));
                    }
                    break;
            }
        }
    };
    private FileAdapter fileAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViewById(R.id.btn_scan_file).setOnClickListener(this);
        rvFileList = findViewById(R.id.rv_file_list);
        tvScanPath = findViewById(R.id.tv_scan_path);
        rvFileList.setLayoutManager(new GridLayoutManager(MainActivity.this,3, GridLayoutManager.VERTICAL,false));
        fileAdapter = new FileAdapter();
        rvFileList.setAdapter(fileAdapter);
    }


    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_scan_file) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                checkAndRequestAllFilePermission();
            } else {
                checkAndRequestStoragePermission();
            }
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.R)
    private void checkAndRequestAllFilePermission() {
        if (Environment.isExternalStorageManager()) {
            startScan();
        } else {
            if (goSettingDialog == null) {
                goSettingDialog = new AlertDialog.Builder(MainActivity.this)
                        .setTitle("需要所有文件权限")
                        .setPositiveButton("去授权", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Uri uri = Uri.parse("package:" + getPackageName());
                                Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION, uri);
                                try {
                                    startActivityForResult(intent, REQUEST_WRITE_EXTERNAL_STORAGE);
                                } catch (ActivityNotFoundException exception) {
                                    requestManageAllFilePermission2();
                                }
                            }
                        }).create();
            }
            goSettingDialog.show();
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.R)
    private void requestManageAllFilePermission2() {
        Intent backupIntent = new Intent();
        backupIntent.setAction(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
        try {
            startActivityForResult(backupIntent, REQUEST_WRITE_EXTERNAL_STORAGE);
        } catch (ActivityNotFoundException backupException) {
            backupException.printStackTrace();
        }
    }


    private void checkAndRequestStoragePermission() {
        try {
            if (checkStoragePermission()) {
                // 检测到有权限，直接下一步
                startScan();
            } else {
                ActivityCompat.requestPermissions(this,
                        new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        REQUEST_WRITE_EXTERNAL_STORAGE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private boolean checkStoragePermission() {
        return ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED &&
                ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        switch (requestCode) {
            case REQUEST_WRITE_EXTERNAL_STORAGE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    startScan();
                } else {
                    if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                        checkAndRequestStoragePermission();
                    } else {
                        if (goSettingDialog == null) {
                            goSettingDialog = new AlertDialog.Builder(MainActivity.this)
                                    .setTitle("需要存储权限")
                                    .setPositiveButton("授权", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            Uri packageURI = Uri.parse("package:" + getPackageName());
                                            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                                            startActivityForResult(intent, requestCode);
                                        }
                                    }).create();
                        }
                        goSettingDialog.show();
                    }
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case REQUEST_WRITE_EXTERNAL_STORAGE:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                    if (!Environment.isExternalStorageManager()) {
                        Toast.makeText(this, "no permission", Toast.LENGTH_SHORT).show();
                    } else {
                        startScan();
                    }
                } else {
                    checkAndRequestStoragePermission();
                }
                break;
        }
    }


    private void startScan() {
        ThreadPoolManager.getSingleExecutor().execute(new Runnable() {
            @Override
            public void run() {
                fileList.clear();
                File externalFilesDirs = Environment.getExternalStorageDirectory();
                Log.e("Test_tag", "run: " + externalFilesDirs.getAbsolutePath() );
                ConcurrentLinkedQueue<File> fileQueue = new ConcurrentLinkedQueue<>();
                fileQueue.offer(externalFilesDirs);
                while (!fileQueue.isEmpty()) {
                    File file = fileQueue.poll();
                    if (file == null || !file.exists()) {
                        continue;
                    }
                    File[] files = file.listFiles();
                    if (files == null) {
                        continue;
                    }
                    for (File childFile : files) {
                        if (childFile == null) {
                            continue;
                        }
                        if (childFile.isDirectory()) {
                            fileQueue.offer(childFile);
                        } else {
                            String miniType = FileUtils.getMiniType(childFile);
                            if (!TextUtils.isEmpty(miniType)) {
                                if (miniType.startsWith("image") || miniType.startsWith("gif") || miniType.startsWith("video") ) {
                                    fileList.add(childFile);
                                }
                            }
                        }
                        handler.removeMessages(SCAN_LOADING_PATH);
                        Message message = Message.obtain();
                        message.what = SCAN_LOADING_PATH;
                        message.obj = childFile;
                        handler.sendMessage(message);
                    }
                }
                handler.sendEmptyMessage(SCAN_COMPLETE);
            }
        });
    }


}